package com.wangzhixuan.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.wangzhixuan.aspectj.SystemLog;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.result.PageInfo;
import com.wangzhixuan.commons.utils.ExcelUtil;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.OperLog;
import com.wangzhixuan.model.vo.UserVo;
import com.wangzhixuan.service.IOperLogService;



/**
 * 操作日志记录
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/operlog")
public class OperlogController extends BaseController
{
    private String prefix = "monitor/operlog";

    @Autowired
    private IOperLogService operLogService;

    
    
    @GetMapping("/manager")
    public String manager() {
        return "admin/operlog";
    }
/*
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OperLog operLog)
    {
        startPage();
        List<OperLog> list = operLogService.selectOperLogList(operLog);
        return getDataTable(list);
    }

  */
    
    
    /**
     * 用户管理列表
     *
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(OperLog operLog, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        
        if (StringUtils.isNotBlank(operLog.getLoginName())) {
            condition.put("loginName", operLog.getLoginName());
        }
        if (operLog.getOperIp() != null) {
            condition.put("operIp", operLog.getOperIp());
        }
        if (operLog.getCreatedateStart() != null) {
            condition.put("startTime", operLog.getCreatedateStart());
        }
        if (operLog.getCreatedateEnd() != null) {
            condition.put("endTime", operLog.getCreatedateEnd());
        }
        pageInfo.setCondition(condition);
        operLogService.selectDataGrid(pageInfo);
        return pageInfo;
    }

    @PostMapping("/addLog")
    @ResponseBody
    public Object addLog(@RequestBody OperLog operLog) {
        operLog.setLoginName(getShiroUser().getLoginName());
        operLogService.insertOperlog(operLog);
        Map<String,String> map = new HashMap<>();
        map.put("ret","200");
        map.put("content","ok");
        return map;
    }

    @RequestMapping("/detail/{operId}")
    public String detail(@PathVariable("operId") Long deptId, Model model)
    {
        OperLog operLog = operLogService.selectOperLogById(deptId);
        model.addAttribute("operLog", operLog);
        return prefix + "/detail";
    }
    
    
    @RequestMapping("/execlAll")
	public void execlAll(ModelMap model,HttpServletRequest request,HttpServletResponse response){
    	 List<OperLog> lists = operLogService.selectOperLogList();
		String fileName = "OperLog" + System.currentTimeMillis() + ".xls"; //文件名
		String sheetName = "操作日志列表";//sheet名

		String[] title = new String[]{"模块标题", "请求方法", "操作员名称", "请求url", "IP地址", "创建时间"};//标题

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String[][] values = new String[lists.size()][];
		for (int i = 0; i < lists.size(); i++) {
			values[i] = new String[title.length];
			//将对象内容转换成string
			OperLog obj = lists.get(i);
			values[i][0] = obj.getTitle()+"";
			if(obj.getTitle()==null){
				values[i][0] ="";
			}
			values[i][1] = obj.getMethod()+"";
			if(obj.getMethod()==null){
				values[i][1] ="";
			}
			values[i][2] = obj.getLoginName()+"";
			if(obj.getLoginName()==null){
				values[i][2] ="";
			}
			values[i][3] = obj.getOperIp()+"";
			if(obj.getOperIp()==null){
				values[i][3] ="";
			}
			if(obj.getOperTime()!=null) {
				values[i][5] = sdf.format(obj.getOperTime());
			}else{
				values[i][5] = "";
			}
		}
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);

		//将文件存到指定位置
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void setResponseHeader(HttpServletResponse response, String fileName) {
			try {
				try {
					fileName = new String(fileName.getBytes(),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				response.setContentType("application/vnd..ms-excel");
				/*response.setContentType("application/octet-stream;charset=ISO8859-1");*/
				response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
				response.addHeader("Pargam", "no-cache");
				response.addHeader("Cache-Control", "no-cache");
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	
	
}
